package com.chenxi.test;

import com.chenxi.annotation.mapper.UserMapper;
import com.chenxi.bean.Order;
import com.chenxi.bean.User;
import com.chenxi.mapper.OrderMapper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class MyBatisTestAnnotation {

    private SqlSession sqlSession;

    private UserMapper userMapper;

    @Before
    public void before() {
        InputStream inputStream = null;
        try {
            // 1、获取mybatis的核⼼⽂件的输⼊流
            inputStream = Resources.getResourceAsStream("mybatis-config.xml");
            // 2、加载mybatis的核⼼⽂件的输⼊流，构建⼀个SqlSessionFactory对象。
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
            // 3、生产sqlSession对象，默认开启了事务，且这个事务不会自动提交，增删改需时要手动提交，
            // sqlSession = sqlSessionFactory.openSession();
            // 构造方法传递参数true时，设置自动提交
            sqlSession = sqlSessionFactory.openSession(true);
            // 获取Mapper
            userMapper = sqlSession.getMapper(UserMapper.class);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @After
    public void after() {
        sqlSession.close();
    }

    @Test
    public void insert() {
        User user = new User();
        user.setId(4);
        user.setUsername("ceshi");
        userMapper.insert(user);
    }

    @Test
    public void update() {
        User user = new User();
        user.setId(4);
        user.setUsername("测试");
        userMapper.update(user);
    }

    @Test
    public void delete() {
        userMapper.delete(4);
    }

    @Test
    public void selectList() {
        List<User> userList = userMapper.selectList();
        userList.forEach((user -> {
            System.out.println(user);
        }));
    }

}
